package com.weibo4j.api.authorize;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;
import com.weibo4j.api.util.HttpClientUtil;

public class OAuth4Code {
    private static final String HOST            = "api.weibo.com";

    private static final String DOMAIN          = "https://api.weibo.com";

    private static final String ACCESSTOKEN_URL = "https://api.weibo.com/oauth2/authorize";

    private static final String AUTHORIZE_URL   = "https://api.weibo.com/oauth2/access_token";
    
    

    public static String getToken(String ticket, String redirectUrl, String appKey,
                                  String appSecret, String userName) throws Exception {
        HttpClient client = HttpClientUtil.getHttpClient();

        HttpPost authorizeReq = new HttpPost(ACCESSTOKEN_URL);
        authorizeReq.addHeader("Referer", ACCESSTOKEN_URL + "?client_id=" + appKey
                + "&response_type=code&redirect_uri=" + redirectUrl);
        authorizeReq.addHeader("Host", HOST);
        authorizeReq.addHeader("Origin", DOMAIN);
        authorizeReq.addHeader("Content-Type", "application/x-www-form-urlencoded");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("action", "submit"));
        nvps.add(new BasicNameValuePair("withOfficalFlag", "0"));
        nvps.add(new BasicNameValuePair("ticket", ticket));
        nvps.add(new BasicNameValuePair("isLoginSina", ""));
        nvps.add(new BasicNameValuePair("response_type", "code"));
        nvps.add(new BasicNameValuePair("regCallback", ""));
        nvps.add(new BasicNameValuePair("redirect_uri", redirectUrl));
        nvps.add(new BasicNameValuePair("client_id", appKey));
        nvps.add(new BasicNameValuePair("state", ""));
        nvps.add(new BasicNameValuePair("from", ""));
        nvps.add(new BasicNameValuePair("userId", userName));
        nvps.add(new BasicNameValuePair("password", ""));
        authorizeReq.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        HttpResponse authorizeResp = client.execute(authorizeReq);
        String goalUrl = authorizeResp.getHeaders("Location")[0].getValue();
        String code = goalUrl.replace(redirectUrl + "?code=", "");

        HttpPost tokenReq = new HttpPost(AUTHORIZE_URL);
        List<NameValuePair> nnvps = new ArrayList<NameValuePair>();
        nnvps.add(new BasicNameValuePair("client_id", appKey));
        nnvps.add(new BasicNameValuePair("client_secret", appSecret));
        nnvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
        nnvps.add(new BasicNameValuePair("code", code));
        nnvps.add(new BasicNameValuePair("redirect_uri", redirectUrl));
        tokenReq.setEntity(new UrlEncodedFormEntity(nnvps, Consts.UTF_8));
        HttpResponse tokenResp = client.execute(tokenReq);
        HttpEntity tokenEntity = tokenResp.getEntity();
        StringBuilder tokenStr = new StringBuilder();
        BufferedReader tokenReader = new BufferedReader(new InputStreamReader(
                tokenEntity.getContent(), "utf-8"));
        String line = null;
        while ((line = tokenReader.readLine()) != null) {
            tokenStr.append(line);
        }
        tokenReader.close();
        return JSON.parseObject(tokenStr.toString()).getString("access_token");
    }

}
